#include "../include/threadPool.h"
/* Usage:  */
//虚伪的循环队列初始化
/* int slotidx=0; */
#define NETFD 1024
/* int mapArr(int fd,int *buf,int timewhell_slot){ */
/*     if(fd <0 ||buf ==NULL){ */
/*         printf("invalid fd or NULL buffer"); */
/*         return -1; */
/*     } */
/*     buf[fd]=timewhell_slot; */
/*     return 0; */

/* } */


int circularQueueInit(circular_queue_t *cirQueue){
    for(int i=0;i < QUEUE_CAPACITY;i++){
        cirQueue->slot[i]=NULL; 
    }
    cirQueue->current_slot =0;
    cirQueue->count=0;
    return 0;
}
//虚伪的循环队列添加用户
int addClient(circular_queue_t *cirQueue,int client_fd){
    //移除旧节点
    for (int i = 0; i < QUEUE_CAPACITY; i++) {
        clientNode_t **cur = &cirQueue->slot[i];
        while (*cur != NULL) {
            if ((*cur)->client_fd == client_fd) {
                clientNode_t *temp = *cur;
                *cur = temp->next;
                free(temp);
                cirQueue->count--;
                break;
            }
            cur = &(*cur)->next;
        }
    }
    clientNode_t *node =(clientNode_t *)malloc(sizeof(clientNode_t));
    node->client_fd=client_fd;
    node->last_time=time(NULL);
    node->next=NULL;
    //插入当前槽位的链表头部
    int slotidx =cirQueue->current_slot;
    node->next=cirQueue->slot[slotidx];
    cirQueue->slot[slotidx]=node;
    cirQueue->count++;
    return 0;
}
// 测试打印函数
//int printQueue(circular_queue_t *cirQueue){
//    if(cirQueue ==NULL ||cirQueue->count ==0){
//        printf("QUEUE is empty.\n");
//        return 0;
//    }
//    printf("Current Slot: %d | Total Clients: %d\n", 
//           cirQueue->current_slot, 
//           cirQueue->count);
//    for (int i = 0; i < QUEUE_CAPACITY; i++) {
//        printf("Slot[%d]: ", i);
//        clientNode_t *node = cirQueue->slot[i];
//        while (node != NULL) {
//            printf("%d(fd:%d, t:%ld) -> ", i, node->client_fd, node->last_time%30);
//            node = node->next;
//        }
//        printf("NULL\n");
//    }
//    return 0;
//}
//模拟时间轮 移动槽位
void tick(circular_queue_t *q) {
    q->current_slot = (q->current_slot + 1) % QUEUE_CAPACITY;  // 环形移动
    printf("\n--- 移动到槽位 [%d] ---\n", q->current_slot);
}

//出队,超时踢人
int checkTimeout(circular_queue_t *cirQueue,int timeout){
    // 检测上一轮的槽位（current_slot - 1）
    int slot_to_check = (cirQueue->current_slot - 1 + QUEUE_CAPACITY) % QUEUE_CAPACITY;
    //指向当前槽位的指针
    clientNode_t **cur =&cirQueue->slot[slot_to_check];
    if(cirQueue->count==0){
        printf("queue is empty.\n");
        return -1;
    }
    while(*cur!= NULL){
        //超时
        if(time(NULL)-(*cur)->last_time >=timeout){
            clientNode_t *temp =*cur;//保存当前节点
            *cur =(*cur)->next;//移除节点
            printf("kick client FD=%d\n",temp->client_fd);
            close(temp->client_fd);  //关闭文件描述符踢出，还未实装
            free(temp);
            cirQueue->count--;
        }
        else{
            cur =&(*cur)->next; //移动到下一节点
        }
    }
    return 0;
}
